import React, { useState } from 'react';
import { Button, Modal, Upload, message, Spin } from 'antd';
import { TRAlert, TRDefault } from '#/components/index.js';
import { DownloadOutlined } from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';

import type { IPublishInfoDataType } from '../../../type';
import { getTemplate } from '../../../service';
import { handleDownload } from '../../../tool';
import styles from './index.less';

interface IProps {
  /**
   * 数据
   */
  record?: IPublishInfoDataType;
  onPress: (data: Record<string, any>) => void;
  onOk?: (params?: any) => void;
}

const ImportModalComponent = (props: IProps) => {
  const { onPress, record, onOk } = props;
  const [visible, setVisible] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [isEdit, setIsEdit] = useState<boolean>(false);
  const [templateId, setTemplateId] = useState<string>();
  const [fileInfo, setFileInfo] = useState<any>();
  const disabled = !fileInfo;

  // 获取模版id
  const getTemplateList = async () => {
    setLoading(true);
    setError(false);
    const res = await getTemplate();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      setTemplateId(res?.data);
    } else {
      setTemplateId(undefined);
      message.info(res?.message || '请求失败');
    }
    setLoading(false);
  };

  // 下载模版
  const onDownLoad = () => {
    handleDownload({ annexId: templateId }, false);
  };

  // 取消按钮
  const _onCancel = async () => {
    if (isEdit) {
      const res = await TRAlert.show('当前工作将不被保存，继续执行此操作？');
      if (res.index === 1) {
        setVisible(false);
        onPress({ index: 0 });
      }
    } else {
      setVisible(false);
      onPress({ index: 0 });
    }
  };

  const _onOk = async () => {
    if (onOk) {
      setIsLoading(true);
      const pdata = new window.FormData();
      pdata.append('file', fileInfo);
      pdata.append('fileName', fileInfo?.name);
      pdata.append('name', fileInfo?.name);
      const res: any = onOk && (await onOk(pdata));
      if (res && res.statusCode === HttpCode.SUCCESS) {
        setVisible(false);
        onPress({ index: 1, statusCode: HttpCode.SUCCESS });
      }
      setIsLoading(false);
    }
  };

  const handleChange = async ({ file }: any) => {
    if (file.status === 'removed') {
      setFileInfo(undefined);
    }
    setIsEdit(true);
  };

  const customRequest = async ({ file }: any) => {
    if (file.status !== 'uploading' && file.status !== 'removed') {
      setFileInfo(file);
    }
    setIsEdit(true);
  };

  React.useEffect(() => {
    getTemplateList();
  }, [record]);

  const footerRender = () => {
    return [
      <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
        取消
      </Button>,
      <Button key="dtest2" type="primary" onClick={_onOk} loading={isLoading} disabled={disabled}>
        确定
      </Button>,
    ];
  };

  return (
    <Modal
      className={styles.modal}
      centered
      width={408}
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>导入</span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'error'} message={'系统异常'} />
        ) : (
          <div className={styles.center}>
            <div className={styles.title}>
              <div className={styles.import}>导入</div>
              <div className={styles.uploadTemplate} onClick={onDownLoad}>
                下载模板
              </div>
            </div>
            <div className={styles.fileContent}>
              <Upload
                customRequest={(e) => customRequest(e)}
                onChange={(e) => handleChange(e)}
                maxCount={1}
                // @ts-ignore
                fileList={fileInfo ? [fileInfo] : []}
                accept=".xls,.xlsx"
              >
                {!fileInfo && (
                  <Button type="primary" ghost icon={<DownloadOutlined />}>
                    导入
                  </Button>
                )}
              </Upload>
            </div>
          </div>
        )}
      </div>
    </Modal>
  );
};

class ImportModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <ImportModalComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new ImportModal();
